package com.fashop.dao.impl;

import javax.annotation.Resource;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.springframework.stereotype.Service;

import com.fashop.bean.beacon.BeaconIn;
import com.fashop.dao.BeaconDao;
import com.fashop.jpa.Beacon;

@Service("beaconDaoImpl")
public class BeaconDaoImpl implements BeaconDao {
	
	@Resource(name = "sessionFactory")
	private SessionFactory factoria;
	
	public Beacon crear() {
		// TODO Auto-generated method stub
		return null;
	}
	public Beacon eliminar() {
		// TODO Auto-generated method stub
		return null;
	}
	
	public Long getIdBeacon(final String uuid, final String proximidad) {
		Session 	 sesion		= null;
		String 		 idBeacon	= null;
		Beacon	 beacon		= null;
		try{
			sesion 	  = factoria.openSession();
			beacon  = (Beacon) sesion.createQuery("from Beacon "
										   +"where UUID=? and proximidad=?")
						.setString(0, uuid)
						.setString(1, proximidad)
						.uniqueResult();			
			sesion.close();						
		}
		catch(Exception e){
			
			idBeacon = null;
			sesion 	 = null;
		}
		return beacon.getIdbeacon();
	}

	public Integer actualizarVistas(BeaconIn beaconIn) {
		Session sesion		= null;
		Integer resultado 	= null;
		Beacon	beacon		= null;
		Transaction tx		= null;
		try{
			sesion = factoria.openSession();
			tx=sesion.beginTransaction();
			beacon=(Beacon) sesion.get(Beacon.class, beaconIn.getIdbeacon());
			/*beacon= (Beacon) sesion.createQuery("from Beacon where idbeacon=?")
					   .setLong(0, beaconIn.getIdbeacon())
					   .uniqueResult();*/
			beacon.setContador(beacon.getContador()+1);			
			sesion.update(beacon);
			tx.commit();
			sesion.close();			
		}
		catch(Exception e){
			System.out.println(e.getMessage());
			sesion=null;
			tx=null;
		}
		return resultado;
	}

	

}
